package com.example.spinning.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.spinning.bean.Dye;
import com.example.spinning.bean.PaginationResult;
import com.example.spinning.mapper.DyeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * @author bayernxmt
 * @create 2020-07-28-16:37
 */

@Service
@Transactional
public class DyeService {

    @Autowired
    private DyeMapper dyeMapper;

    //查询所有 并且分页展示 : current表示当前页，size表示一页展示多少条数据
    public PaginationResult<Dye> selectAll(int current, int size){
        Page<Dye> pages = new Page<>(current,size);
        dyeMapper.selectPage(pages, null);
        List<Dye> list = pages.getRecords();
        int total = dyeMapper.selectCount(null);

        PaginationResult<Dye> pr = new PaginationResult<>();
        pr.setTotal(total);
        pr.setList(list);
        return pr;
    }

    //单、多条件查询 并且实现分页
    public PaginationResult<Dye> selectByMulParams(int current, int size, Dye dye){

        QueryWrapper<Dye> wrapper = new QueryWrapper();
        if (null!=dye.getBatch_no())
            wrapper.eq("batch_no", dye.getBatch_no());
        if (null!=dye.getName())
            wrapper.eq("name", dye.getName());
        if (null!=dye.getDate())
            wrapper.eq("date", dye.getDate());

        Page<Dye> pages = new Page<>(current,size);
        dyeMapper.selectPage(pages, wrapper);
        int total = dyeMapper.selectCount(wrapper);
        List<Dye> list = pages.getRecords();

        PaginationResult<Dye> pr = new PaginationResult<>();
        pr.setTotal(total);
        pr.setList(list);
        return pr;
    }

    //根据id查询
    public Dye SelectById(int id){
        return dyeMapper.selectById(id);
    }

    //插入数据
    public int insert(Dye dye) {
        dye.setDate(new Timestamp(new Date().getTime()));
        int result = dyeMapper.insert(dye); //result为受到影响的条数
        return result;
    }


    //批量删除数据（与删除一条合并）
    public int delete(List<Integer> ids){
        int result = dyeMapper.deleteBatchIds(ids);
        return result;
    }

    //修改数据(已经实现了动态sql)
    public int update(Dye dye){
        dye.setDate(new Timestamp(new Date().getTime()));
        int result = dyeMapper.updateById(dye);
        return result;
    }

}
